﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

/*
 * 
 * A one-way hash:
 * 
 * System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(UserPassword.Text,"sha1")
 * The word "secret", hashed:
 * 
 * E5E9FA1BA31ECD1AE84F75CAAA474F3A663F05F4
 */
namespace MusicLine
{
    internal class SystemSecurity : AbstractDAL
    {
        public static bool ValidateUser(string UserLogonId, string UserPassword)
        {
            bool UserIsValid = false;

            using (SqlConnection MusicLineConnection = GetConnection())
            {
                SqlCommand ValidateLogonCredentials = new SqlCommand("Exec ValidateLogonCredentials @UserLogonId, @UserPassword", MusicLineConnection);
                ValidateLogonCredentials.Parameters.Add("@UserLogonId", SqlDbType.VarChar).Value = UserLogonId;
                ValidateLogonCredentials.Parameters.Add("@UserPassword", SqlDbType.VarChar).Value = UserPassword;

                MusicLineConnection.Open();

                UserIsValid = int.Parse(ValidateLogonCredentials.ExecuteScalar().ToString()) == 1;
            }

            return UserIsValid;
        }

        public static string[] GetUserRoles(string UserLogonId)
        {
            string[] RolesArray = null;
            using (SqlConnection MusicLineConnection = GetConnection())
            {
                SqlDataAdapter GetUserrolesAdapter = new
                        SqlDataAdapter("Exec GetUserroles @UserLogonId", MusicLineConnection);
                GetUserrolesAdapter.SelectCommand.Parameters.Add
                        ("@UserLogonId", SqlDbType.VarChar).Value = UserLogonId;

                DataSet UserRoles = new DataSet();

                GetUserrolesAdapter.Fill(UserRoles, "Roles");

                //allocate memory for the array of strings
                RolesArray = new string[UserRoles.Tables["Roles"].Rows.Count];
                for (int c = 0; c < RolesArray.Length; c++)
                {
                    RolesArray[c] = UserRoles.Tables["Roles"].Rows[c]["RoleName"].ToString();
                }
            }
            return RolesArray;
        }
    }
}
